class Solution:
    def calcEquation(self, equations, values, queries):
        dic = {}
        for i in equations:
            for k in i:
                if k in dic:
                    continue
                else:
                    dic[k] = {}
                    dic[k][k] = 1
        for k in range(len(equations)):
            i = equations[k]
            i0 = dic[i[0]]
            if i[1] in i0:
                continue
            i1 = dic[i[1]]
            if len(i0) >= len(i1):
                base = i0[i[0]] / values[k] / i1[i[1]]
                for j in i1.keys():
                    i0[j] = (i1[j]) * base
                    dic[j] = i0
            else:
                base = values[k] * i1[i[1]] / i0[i[0]]
                for j in i0.keys():
                    i1[j] = base * (i0[j])
                    dic[j] = i1
        r = []
        for i in queries:
            if i[0] not in dic or i[1] not in dic:
                r.append(-1.0)
                continue
            i0 = dic[i[0]]
            if i[1] not in i0:
                r.append(-1.0)
                continue
            r.append(i0[i[0]]/i0[i[1]])
        return r


if __name__ == '__main__':
    so = Solution()
    equations = [["a", "b"], ["b", "c"]]
    values = [2.0, 3.0]
    queries = [["a", "c"], ["b", "a"], ["a", "e"], ["a", "a"], ["x", "x"]]
    r = so.calcEquation(equations, values, queries)
    print(r)
